<!--
* description: 模板-单网格
* author: zxuan
* createdDate: 2019-09-12
* update: tfy 2019-10-16
* update: dxuem 2020-02-24 多选框增加属性selectable,根据每一行某个数据来判断禁不禁用
* logs:
*
-->
<template>
  <section class="filter-params-e3s">
    <div
      id="searchFormGroup"
      class="filter-container filter-params"
      style="margin:0 0 1px 0"
      v-if="tableComponents.length > 0"
      ref="conHeight"
    >
      <el-row :gutter="24">
        <el-col :span="24">
          <el-row>
            <component
              v-for="(comp,index) in tableComponents.filter(o => o.isMust === false)"
              v-show="dynamicSearchField?toggleParam:index<4?true:toggleParam"
              :ref="comp.isRequire ? comp.isRequire+ comp.compKey : comp.compKey"
              :isshow="comp.isshow"
              :validrule="comp.validrule"
              :key="comp.compKey"
              :codeField="comp.codeField"
              :textField="comp.textField"
              :popupsKey="comp.compKey"
              :is="comp.component"
              :code="formField[comp.codeField]"
              :text="formField[comp.textField]?formField[comp.textField]:''"
              @changeDropValue="getDropValue"
              @changeCode="getComponentCode"
              @focusCode="getFocusCode"
              @getCode="comp.changeCode"
              @emitCode="comp.emitCode"
              :isMul="comp.isMul"
              :chackAll="comp.chackAll"
              :groupType="comp.groupType?comp.groupType:''"
              :isRequire="comp.isRequire"
              :span="comp.span || 6"
              :labelName="comp.labelName"
              :lookuptype="comp.lookuptype"
              :inputType="comp.inputType"
              :dateOptionsType="comp.dateOptionsType"
              :format="comp.format"
              :dateType="comp.dateType"
              :valueObject="curValueObject"
              :clearable="comp.clearable"
              :filterable="comp.filterable"
              :parentFileds="comp.parentFileds || ''"
              :changeCodeArray="comp.changeCodeArray"
              :extralParams="comp.extralParams"
              :disabled="comp.disabled"
              :attribute="comp.attribute"
              :remark="comp.remark"
              :importHref="comp.importHref"
              :importDownload="comp.importDownload"
              :importUrl="comp.importUrl"
              :isTags="comp.isTags"
            ></component>
          </el-row>
        </el-col>
      </el-row>
    </div>
    <div
      class="filter-container filter-button"
      style="background-color:white;margin-top:-1px"
      ref="searcheHeight"
    >
      <el-row style="padding: 5px 20px;">
        <el-button
          :style="comp.isShow?'display:none;':'display:block;float:left'"
          v-for="comp in tableButtons"
          :icon="getIcon(comp)"
          :key="comp.compKey"
          :type="comp.type"
          @click="comp.clickEvent"
          @keyup.enter="comp.clickEvent"
          :class="comp.class||''"
        >{{comp.text}}{{comp.showCount&&selectedLength>0 ? '（'+selectedLength+'）' : ''}}</el-button>
        <el-col
          v-show="tableComponents.length<=4?toggleParam:!toggleParam"
          style="width:90px;float:right;"
        >
          <el-col :span="2" class="moreBtn" style="float:right" v-if="isShowMoreBtn">
            <el-button
              style="float:right;width:90px;border:0"
              :icon="moreBtnIcon"
              @click="changeToggleParam"
              class
            >高级搜索</el-button>
          </el-col>
        </el-col>
        <el-col
          v-show="dynamicSearchField?toggleParam:true"
          style="width: 30%;float: right;max-width: 400px;"
        >
          <el-button
            v-show="tableComponents.length<=4?false:toggleParam"
            style="float:right;width:90px;border:0"
            :icon="moreBtnIcon"
            @click="changeToggleParam"
            class
          >收起</el-button>
          <el-col
            :span="2"
            class="moreBtn"
            :style="dynamicButtonsRightSpan"
            style="float:right;"
            v-if="isShowMoreBtn"
          >
            <el-button
              style="float:right;margin-left:10px;"
              v-for="comp in tableButtonsRight.length>0?tableButtonsRight:tableButton1"
              :icon="comp.icon"
              :key="comp.compKey"
              :type="comp.type"
              @click="comp.clickEvent"
            >{{comp.text}}</el-button>
          </el-col>
        </el-col>
        <el-col v-show="!toggleParam&&dynamicSearchField" style="width:400px;float:right;">
          <el-input
            class="crm-common-search"
            style="width:300px;border-right: 0;float:left;margin:1px"
            v-model="queryParam"
            :placeholder="searchField"
            size="small"
          ></el-input>
          <el-button
            icon="el-icon-search"
            @click="query()"
            class="el-button--primary crmonepage-searchButton"
          >搜索</el-button>
        </el-col>
      </el-row>
    </div>

    <!-- <div
      class="filter-container filter-title"
      ref="resultTitleHeight"
    >查询结果</div>-->
    <!-- <img v-show="listLoading" alt src="Images/crm/carLoading.gif" class="el-loading-crm-spinner-mainTable " :style="topHeight" /> -->
    <el-table
      v-if="haveTable"
      class="crmonepage-hello"
      :data="list"
      v-loading="listLoading"
      :element-loading-text="$store.state.app.loadingText"
      border
      :span-method="arraySpanMethod"
      stripe
      :height="tableHeight"
      header-cell-class-name="header-cell"
      highlight-current-row
      ref="multipleTable"
      @current-change="handleTableRowChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        align="center"
        type="selection"
        v-if="isShowSelect"
        :fixed="!isRowDrop"
        width="55"
        :label="$t('sys.content.gridChoose')+'+'"
        filed="chose"
        current-row-key="choose"
        :selectable="selectable"
      />
      <el-table-column
        align="center"
        :fixed="!isRowDrop"
        :label="$t('sys.content.gridIndex')"
        width="60"
        type="index"
      >
        <template slot-scope="{row}">
          <span>{{(listIndex.pageIndex - 1) * listIndex.pageSize + row.index + 1}}</span>
        </template>
      </el-table-column>
      <template v-for="(col, index) in tableCols.filter(o => o.hidden !== true)">
        <table-column
          v-if="col.children && col.children.length"
          :key="`column_${index}`"
          :coloumn-header="col"
        />
        <el-table-column
          v-if="!col.children"
          :fixed="(dropTableCols[index].fixed || false) && !isRowDrop"
          :label="col.label"
          :key="`col_${index}`"
          :prop="dropTableCols[index].prop"
          :width="dropTableCols[index].width || null"
          :min-width="dropTableCols[index].minWidth || null"
          :hidden="dropTableCols[index].hidden"
          :align="dropTableCols[index].align"
          :sortable="dropTableCols[index].sortable || sortable"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="{row}">
            <span v-if="dropTableCols[index].isComponent === true && dropTableCols[index].comps">
              <component
                v-for="comp in dropTableCols[index].comps"
                :key="comp.compKey"
                :is="comp.component"
                :codeField="comp.codeField"
                :textField="comp.textField"
                :popupsKey="comp.compKey"
                :isShow="row[comp.compareField]===comp.compareValue"
                :code="row[comp.codeField]"
                :text="row[comp.textField]"
                @changeCode="getRowComponentCode"
                @clickEvent="comp.clickEvent"
                :comType="row.index+''"
                :isMul="comp.isMul"
                :span="dropTableCols[index].span || 24"
                :isShowLabel="comp.isShowLabel"
                :labelName="comp.labelNameArray?(row[comp.labelNameArray[0]]==comp.labelNameArray[1][0].split(',')[0]?comp.labelNameArray[1][0].split(',')[1]:comp.labelNameArray[1][1].split(',')[1]):comp.labelName"
                :lookuptype="comp.lookuptype"
                :format="comp.format"
                :dateType="comp.dateType"
                :dateOptionsType="comp.dateOptionsType"
                :contWay="[row,comp.contWay]"
                :clearable="comp.clearable"
                :filterable="comp.filterable"
                :curTableRow="comp.rowFileds?row:null"
                :rowFileds="comp.rowFileds"
                :disabled="row[comp.disabled]"
              ></component>
            </span>
            <span
              v-else-if="!dropTableCols[index].isComponent&&col.showLink"
              class="link"
              @click="col.clickEvent(row)"
            >{{row[dropTableCols[index].prop]}}</span>
            <!-- <span
            v-else-if="!dropTableCols[index].isComponent && dropTableCols[index].prop === 'isEnable'"
            >{{(row[dropTableCols[index].prop] === '1') ? '是' : '否' }}</span>-->
            <span
              v-else
            >{{ dropTableCols[index].prop=='daysLeftName'?'':row[dropTableCols[index].prop] }}</span>
            <span
              v-if="!dropTableCols[index].isComponent && dropTableCols[index].prop === 'daysLeftName'"
            >
              <i
                v-if="row[dropTableCols[index].prop]=='预计回访时间今明后三天的客户' && row[dropTableCols[index].prop]"
                class="el-icon-phone-outline"
                title="预计回访时间今明后三天的客户"
                style="color:#00f;fontSize:20px;"
              ></i>
              <i
                v-if="row[dropTableCols[index].prop]=='预计回访时间超期客户' && row[dropTableCols[index].prop]"
                class="el-icon-phone-outline"
                title="预计回访时间超期客户"
                style="color:#f00;fontSize:20px;"
              ></i>
            </span>
            <span
              v-if="!dropTableCols[index].isComponent && dropTableCols[index].prop === ''&&col.qudao"
            >
              <span
                class="qudao"
                :class="[row['isEnable']=='0'?'activeClass1':'activeClass2']"
                @click="col.clickEvent(row,1)"
              >微信模板消息</span>
              <span
                class="qudao"
                :class="[row['isEnable']=='0'?'activeClass1':'activeClass2']"
                @click="col.clickEvent(row,2)"
              >短信</span>
              <span class="qudao" @click="col.clickEvent(row,3)">48小时客户消息</span>
            </span>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-pagination
      background
      v-if="noTablePage?false:haveTable"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[10, 20, 30]"
      :page-size="listQuery.pageSize"
      prev-text="上一页"
      next-text="下一页"
      layout="prev, pager, next, sizes, ->, total"
      ref="paginationHeight"
      :total="pageTotal"
      :current-page.sync="listQuery.pageIndex"
    ></el-pagination>
    <div
      v-show="isOver"
      class="page-ScrollButton"
      :class="getBtnClass('left')"
      @click="leftScroll(3)"
    >
      <i class="el-icon-caret-left"></i>
    </div>
    <div
      v-show="isOver"
      class="page-ScrollButton"
      :class="getBtnClass('right')"
      @click="rightScroll(3)"
    >
      <i class="el-icon-caret-right"></i>
    </div>
    <!-- <div
     v-if="isOver"  
     :class="isDefaultLeft?'crm-page-leftScrollButton-default':'crm-page-leftScrollButton-click'"   
      @click="leftScroll(3)"><i class="el-icon-caret-left"></i></div>
    <div v-if="isOver" :class="isDefaultRight?'crm-page-rightScrollButton-default':'crm-page-rightScrollButton-click'"   @click="rightScroll(3)"><i class="el-icon-caret-right"></i></div>-->
    <div v-show="tableComponents.filter(o => o.type === 'popupsInput').length > 0">
      <component
        v-for="comp in tableComponents.filter(o => o.type === 'popupsInput')"
        :key="comp.popups.key"
        :codeField="comp.codeField"
        :popupsVisible="comp.popups.state"
        :comType="comp.popups.type"
        :is="comp.popups.component"
        :popupsKey="comp.compKey"
        :code="formField[comp.codeField]"
        @changeCode="getComponentCode"
        :valueObject="curValueObject"
      ></component>
    </div>
  </section>
</template>
<script>
import { oneTableTemplateMixins } from "@/components/mixins/oneTableTemplateMixinsCrm";
import { valueObjectMixins } from "@/components/mixins/valueObjectMixins";
import { contsMixins } from "@/components/mixins/contsMixins";
import tableColumn from "./crmTableColumn";
export default {
  // 组件混入对象：{data[listQuery] methods[queryTable]}
  mixins: [oneTableTemplateMixins, valueObjectMixins, contsMixins],
  components: {
    tableColumn
  },
  props: {
    isInt: { type: Boolean, default: false }, //查询条件是否有格式要求
    dynamicSearchField: { type: String, default: "" }, //placerholder
    dynamicSearchValue: { type: String, default: "" }, //高级搜索模糊查询值
    selectable: {
      type: Function,
      default: function() {
        return true;
      }
    },
    labelNameArray: {
      type: Array,
      default: function() {
        return [];
      }
    },
    dynamicButtonsRight: {
      type: Array,
      default: function() {
        return [];
      }
    },
    dynamicButtonsRightSpan: {
      type: Object,
      default: function() {
        return { width: "65%" };
      }
    },
    // 合并行、列函数
    arraySpanMethod: { type: Function, default: () => {} },
    haveTable: { type: Boolean, default: true },
    noTablePage: { type: Boolean, default: false }
    // isOver:{ type: Boolean, default: false }
    //dynamicFormFields:{ type: Object, default: {} }
  },
  watch: {
    queryParam(value) {
      this.$parent.queryParam != undefined
        ? (this.$parent.formField.queryParam = value)
        : "";
    }
  },
  mounted() {
    let that = this;
    that.$nextTick(function() {
      //  document.getElementById('AppMain').style.overflowY='hidden'
      that.isOverWidth();
      // window.addEventListener('scroll', that.handleScroll, true)
    });
  },
  destroyed() {
    // 离开该页面需要移除这个监听的事件，不然会报错
    window.removeEventListener("scroll", this.handleScroll);
  },
  data() {
    return {
      selectedLength: "",
      // haveTable: this.haveTable,
      isOver: false,
      isDefaultLeft: true,
      isDefaultRight: false,
      searchField: this.dynamicSearchField,
      queryParam: this.dynamicSearchValue,
      tableButtonsRight: this.dynamicButtonsRight,
      topHeight: "",
      scrollLeft: "",
      moreBtnIcon: "iconfont icon-dowm",
      iindex: 0, //当前滚动的角标
      //formField:this.dynamicFormFields,
      tableButton1: [
        {
          compKey: "btnKey10001",
          type: "",
          size: "small",
          icon: "iconfont icon-reset",
          clickEvent: () => this.resetEx(),
          text: "重置"
        },
        {
          compKey: "btnKey10000",
          type: "primary",
          icon: "iconfont icon-search",
          size: "small",
          clickEvent: () => this.query(),
          text: "查询"
        }
      ]
    };
  },
  methods: {
    // 左右按钮点击滑动距离判断
    leftScroll(num) {
      // 获取移动个数列的宽度
      // 1.获取非固定列的数组
      if (this.iindex > 0) {
        let allColumnArr = document
          .querySelector(".crmonepage-hello .el-table__header")
          .getElementsByTagName("th");
        let columnWidthArr = [];
        for (var i = 0; i < allColumnArr.length; i++) {
          if (allColumnArr[i].classList[2] != "is-hidden") {
            // 剔除固定列
            columnWidthArr.push(allColumnArr[i].offsetWidth);
          }
        }
        // 左滑动完成，终止
        if (this.iindex <= 0) {
          this.isDefaultLeft = true;
          this.isDefaultRight = false;
          return;
        }
        // scrollLeft距离
        var moveDistance = 0;
        this.iindex = this.iindex - num;
        if (this.iindex > 0) {
          for (var i = 0; i < columnWidthArr.length; i++) {
            moveDistance = moveDistance + parseFloat(columnWidthArr[i]);
            //  遍历到滚动的节点，终止
            if (i == this.iindex - 1) {
              break;
            }
          }
        }
      }

      if (this.$refs.multipleTable.$refs.bodyWrapper.scrollLeft > 0) {
        this.$refs.multipleTable.$refs.bodyWrapper.style.scrollBehavior =
          "smooth";
        this.$refs.multipleTable.$refs.bodyWrapper.scrollLeft = moveDistance;
        this.isDefaultLeft = false;
        this.isDefaultRight = false;
        return;
      }
      if (this.$refs.multipleTable.$refs.bodyWrapper.scrollLeft == 0) {
        this.$refs.multipleTable.$refs.bodyWrapper.style.scrollBehavior =
          "smooth";
        this.$refs.multipleTable.$refs.bodyWrapper.scrollLeft = 0;
        this.isDefaultLeft = true;
        this.isDefaultRight = false;
        return;
      }
    },
    rightScroll(num) {
      const that = this;

      // 获取移动个数列的宽度
      // 1.获取非固定列的数组
      const allColumnArr = document
        .querySelector(".crmonepage-hello .el-table__header")
        .getElementsByTagName("th");
      const columnWidthArr = [];
      for (var i = 0; i < allColumnArr.length; i++) {
        if (allColumnArr[i].classList[2] !== "is-hidden") {
          // 剔除固定列
          columnWidthArr.push(allColumnArr[i].offsetWidth);
        }
      }
      // 右滑动完成，终止
      if (that.iindex >= columnWidthArr.length) {
        that.isDefaultLeft = false;
        that.isDefaultRight = true;
        return;
      }
      if (that.isDefaultRight === true) {
        return;
      }

      var moveDistance = 0;
      that.iindex = that.iindex + num;
      for (let i = 0; i < columnWidthArr.length; i++) {
        moveDistance = moveDistance + parseFloat(columnWidthArr[i]);
        //  遍历到滚动的节点，终止
        if (i === that.iindex - 1) {
          break;
        }
      }
      this.$refs.multipleTable.$refs.bodyWrapper.style.scrollBehavior =
        "smooth";
      this.$refs.multipleTable.$refs.bodyWrapper.scrollLeft = moveDistance;
      //  scrollLeft距离
      // 固定列宽度
      // let fixedWidth = document.querySelector('.crmonepage-hello .el-table__fixed').getBoundingClientRect().width
      //  框架宽度
      const frameworkWidth = document
        .querySelector(".filter-params-e3s")
        .getBoundingClientRect().width;
      //  所有列宽度
      const allColumWidth = document
        .querySelector(".crmonepage-hello .el-table__header")
        .getBoundingClientRect().width;
      const scrollLeftWidth = allColumWidth - frameworkWidth;
      if (moveDistance >= parseFloat(scrollLeftWidth)) {
        that.isDefaultLeft = false;
        that.isDefaultRight = true;
      } else {
        that.isDefaultLeft = false;
        that.isDefaultRight = false;
      }
      return;
    },
    // 下拉框联动

    getDropValue(val, txt, comName) {
      let that = this;
      that.$refs[comName]
        ? that.$refs[comName][0].getData(val, txt, comName)
        : "";
      that.$refs[comName] ? (that.$refs[comName][0].modelCode = "") : "";
    },
    getIcon(comp) {
      var text = comp.text;
      if (text.indexOf("新增") != -1) {
        comp.type = "";
        return "iconfont icon-newlyAdded";
      }
      if (text.indexOf("导出") != -1) {
        comp.type = "";
        return "iconfont icon-export";
      }
      if (text.indexOf("导入") != -1) {
        comp.type = "";
        return "iconfont icon-importTemplate";
      }
      if (text.indexOf("确认") != -1) {
        comp.type = "";
        return "iconfont  icon-confirm";
      }
    },
    query() {
      let that = this;
      for (let key in that.formField) {
        if (that.formField[key] === " ") {
          that.formField[key] = undefined;
        }
      }
      if (this.tableButtonsRight.length > 0) {
        this.$parent.query();
        return;
      }
      this.queryTable(1);
    },
    resetEx() {
      let that = this;
      let patt = new RegExp(",");
      for (let key in that.$refs) {
        if (that.$refs[key][0] && that.$refs[key][0].codeField) {
          let flag = patt.test(that.$refs[key][0].codeField);
          if (flag) {
            that.$refs[key][0].modelCode = [];
          }
        }
      }
      this.reset();
    },
    changeToggleParam() {
      this.toggleParam = !this.toggleParam;
      if (this.toggleParam) {
        this.moreBtnIcon = "iconfont icon-up";
      } else {
        this.moreBtnIcon = "iconfont icon-dowm";
      }
      // 本人当日待回访线索
      if (this.tableButtonsRight.length > 0 && this.$parent.reset1) {
        this.$parent.reset1();
      }

      // 收缩时清空查询条件
      if (this.dynamicSearchField) {
        this.resetEx();
      }
      this.queryParam = "";
      this.setTableHeight();
      //change 抛出事件
      this.$emit("changeToggleProp");
      //   this.topHeight=this.topHeightFuc()
    },
    isOverWidth() {
      // 所有网格元素宽度
      let that = this;
      let allColumnWidth =
        document
          .querySelector(".crmonepage-hello .el-table__header")
          .getBoundingClientRect().width + 1;
      //框架右侧宽度
      let frameWidth = document
        .querySelector(".filter-params-e3s")
        .getBoundingClientRect().width;
      if (allColumnWidth > frameWidth) {
        that.isOver = true;
        //出现左右滑动按钮
      } else {
        that.isOver = false;
      }
    },
    // 获取滚动条左右移图标
    getBtnClass(type) {
      let className = "";
      if (
        (type === "left" && this.isDefaultLeft) ||
        (type === "right" && this.isDefaultRight)
      ) {
        className = "page-" + type + "ScrollButton-default";
      } else {
        className = "page-" + type + "ScrollButton-click";
      }
      // 是否包含分页组件
      if (this.isShowPagination === false || this.tableCols.length === 0) {
        if (this.isIE) {
          className += " page-scrollButton-noPage-ie";
        } else {
          className += " page-scrollButton-noPage";
        }
      } else {
        if (this.isIE) {
          className += " page-scrollButton-ie";
        }
      }
      return className;
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val;
      if (this.isInt) {
        this.$parent.query();
        return;
      }
      this.queryTable();
    },
    // 当前页记录
    handleCurrentChange(val) {
      this.listQuery.pageIndex = val;
      if (this.isInt) {
        this.$parent.query(val);
        return;
      }
      this.queryTable();
    }
  }
};
</script>
<style scoped>
.crm-common-search .el-input__inner {
  border-bottom-right-radius: 0;
  border-top-right-radius: 0;
}
.link {
  color: #0077ff;
  text-decoration: underline;
}
.link:hover {
  cursor: pointer;
}
.crmonepage-searchButton {
  padding: 0;
  margin: 0;
  border-left: 0px;
  float: left;
  height: 24px;
  margin: 1px 0 1px -5px;
  border-radius: 0;
}
.crmonepage-hidden {
  display: none;
}
.crmonepage-hello {
  -webkit-transition-duration: 500ms;
  -moz-transition-duration: 500ms;
  -ms-transition-duration: 500ms;
  -o-transition-duration: 500ms;
  transition-duration: 500ms;
}
.qudao {
  margin-right: 5px;
  color: #aaa;
}
.qudao:hover {
  cursor: pointer;
}
.activeClass1 {
  color: #0077ff;
}
.activeClass2 {
  color: #f00;
}
</style>
